home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / arcers / tar316.zip / DISZIP.C < prev    next >
Text File  |  1994-06-29  |  38KB  |  1,037 lines

  1. /* The following is derived from 'funzip' utility sources
  2.  * (funzip.c & inflate.c files) which are written and
  3.  * gracefully put into public domain by Mark Adler.
  4.  * You can find original texts in Info-Zip 'unzip' distribution.
  5.  */
  6.  
  7. /*#define PKZIP_BUG_WORKAROUND*/
  8. #define V314_BUG_WORKAROUND
  9.  
  10. #include "modern.h"
  11. #include "stdinc.h"
  12. #ifdef MODERN
  13. #  include <string.h>
  14. #else
  15.    char *malloc();
  16. #endif
  17. #include "zipdefs.h"
  18. #include "zippipe.h"
  19. #include "crc32.h"
  20.  
  21. #ifndef max
  22. #  define max(a,b) (((a) > (b)) ? (a) : (b))
  23. #endif
  24.  
  25. /* Minix needs it after all the other includes (?) */
  26. #include <stdio.h>
  27.  
  28. #define AT_EOF 0x80 /* End of data achieved */
  29. #define INITED 0x40 /* Header processed */
  30. #define METHOD 0x03 /* Inflate method mask */
  31. #define IBEGIN 0x20 /* Trees (or stored length) processed */
  32. #define ICFLAG 0x10 /* Copy pending */
  33.  
  34. static uch zipstate = 0;
  35. static int (*getb) __ARGS__((void)) = (int(*)())0;
  36.  
  37. #define readbyte() (*getb)()
  38. #define nextbyte() (*getb)()
  39.  
  40. #define PF_CRYPT 1 /* PKWare flag fields */
  41. #define PF_ATEOF 8
  42. #define PF_ERROR 0x1ff0
  43.  
  44. #define GF_ASCII   1 /* GNU flag fields */
  45. #define GF_CONT    2
  46. #define GF_EXTRA   4
  47. #define GF_FNAME   8
  48. #define GF_COMMENT 0x10
  49. #define GF_CRYPT   0x20
  50. #define GF_ERROR   0xC0
  51.  
  52. static char ziptype = 0;
  53. static ush zipflags, zmethod;
  54. static ulg crc32val, srcsize;
  55.        uch *slide = (uch*)0;
  56. static ulg outsiz;  /* total bytes written to out */
  57. static char *outbuf;
  58. static ush  outpos; /* output posiztion in slide */
  59.  
  60. /*
  61.    Inflate deflated (PKZIP's method 8 compressed) data.  The compression
  62.    method searches for as much of the current string of bytes (up to a
  63.    length of 258) in the previous 32K bytes.  If it doesn't find any
  64.    matches (of at least length 3), it codes the next byte.  Otherwise, it
  65.    codes the length of the matched string and its distance backwards from
  66.    the current position.  There is a single Huffman code that codes both
  67.    single bytes (called "literals") and match lengths.  A second Huffman
  68.    code codes the distance information, which follows a length code.  Each
  69.    length or distance code actually represents a base value and a number
  70.    of "extra" (sometimes zero) bits to get to add to the base value.  At
  71.    the end of each deflated block is a special end-of-block (EOB) literal/
  72.    length code.  The decoding process is basically: get a literal/length
  73.    code; if EOB then done; if a literal, emit the decoded byte; if a
  74.    length then get the distance and emit the referred-to bytes from the
  75.    sliding window of previously emitted data.
  76.  
  77.    There are (currently) three kinds of inflate blocks: stored, fixed, and
  78.    dynamic.  The compressor outputs a chunk of data at a time, and decides
  79.    which method to use on a chunk-by-chunk basis.  A chunk might typically
  80.    be 32K to 64K, uncompressed.  If the chunk is uncompressible, then the
  81.    "stored" method is used.  In this case, the bytes are simply stored as
  82.    is, eight bits per byte, with none of the above coding.  The bytes are
  83.    preceded by a count, since there is no longer an EOB code.
  84.  
  85.    If the data is compressible, then either the fixed or dynamic methods
  86.    are used.  In the dynamic method, the compressed data is preceded by
  87.    an encoding of the literal/length and distance Huffman codes that are
  88.    to be used to decode this block.  The representation is itself Huffman
  89.    coded, and so is preceded by a description of that code.  These code
  90.    descriptions take up a little space, and so for small blocks, there is
  91.    a predefined set of codes, called the fixed codes.  The fixed method is
  92.    used if the block ends up smaller that way (usually for quite small
  93.    chunks), otherwise the dynamic method is used.  In the latter case, the
  94.    codes are customized to the probabilities in the current block, and so
  95.    can code it much better than the pre-determined fixed codes can.
  96.  
  97.    The Huffman codes themselves are decoded using a mutli-level table
  98.    lookup, in order to maximize the speed of decoding plus the speed of
  99.    building the decoding tables.  See the comments below that precede the
  100.    lbits and dbits tuning parameters.
  101.  */
  102.  
  103. /*
  104.    Notes beyond the 1.93a appnote.txt:
  105.  
  106.    1. Distance pointers never point before the beginning of the output
  107.       stream.
  108.    2. Distance pointers can point back across blocks, up to 32k away.
  109.    3. There is an implied maximum of 7 bits for the bit length table and
  110.       15 bits for the actual data.
  111.    4. If only one code exists, then it is encoded using one bit.  (Zero
  112.       would be more efficient, but perhaps a little confusing.)  If two
  113.       codes exist, they are coded using one bit each (0 and 1).
  114.    5. There is no way of sending zero distance codes--a dummy must be
  115.       sent if there are none.  (History: a pre 2.0 version of PKZIP would
  116.       store blocks with no distance codes, but this was discovered to be
  117.       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
  118.       zero distance codes, which is sent as one code of zero bits in
  119.       length.
  120.    6. There are up to 286 literal/length codes.  Code 256 represents the
  121.       end-of-block.  Note however that the static length tree defines
  122.       288 codes just to fill out the Huffman codes.  Codes 286 and 287
  123.       cannot be used though, since there is no length base or extra bits
  124.       defined for them.  Similarily, there are up to 30 distance codes.
  125.       However, static trees define 32 codes (all 5 bits) to fill out the
  126.       Huffman codes, but the last two had better not show up in the data.
  127.    7. Unzip can check dynamic Huffman blocks for complete code sets.
  128.       The exception is that a single code would not be complete (see #4).
  129.    8. The five bits following the block type is really the number of
  130.       literal codes sent minus 257.
  131.    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
  132.       (1+6+6).  Therefore, to output three times the length, you output
  133.       three codes (1+1+1), whereas to output four times the same length,
  134.       you only need two codes (1+3).  Hmm.
  135.   10. In the tree reconstruction algorithm, Code = Code + Increment
  136.       only if BitLength(i) is not zero.  (Pretty obvious.)
  137.   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
  138.   12. Note: length code 284 can represent 227-258, but length code 285
  139.       really is 258.  The last length deserves its own, short code
  140.       since it gets used a lot in very redundant files.  The length
  141.       258 is special since 258 - 3 (the min match length) is 255.
  142.   13. The literal/length and distance code bit lengths are read as a
  143.       single stream of lengths.  It is possible (and advantageous) for
  144.       a repeat code (16, 17, or 18) to go across the boundary between
  145.       the two sets of lengths.
  146.  */
  147. /* Huffman code lookup table entry--this entry is four bytes for machines
  148.    that have 16-bit pointers (e.g. PC's in the small or medium model).
  149.    Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
  150.    means that v is a literal, 16 < e < 32 means that v is a pointer to
  151.    the next table, which codes e - 16 bits, and lastly e == 99 indicates
  152.    an unused code.  If a code with e == 99 is looked up, this implies an
  153.    error in the data. */
  154.  
  155. #define EOB     15
  156. #define LITERAL 16
  157. #define BAD     99
  158.  
  159. typedef struct _huft {
  160.   uch e; /* number of extra bits or operation */
  161.   uch b; /* number of bits in this code or subcode */
  162.   union {
  163.     ush n; /* literal, length base, or distance base */
  164.     struct _huft *t; /* pointer to next level of table */
  165.   } v;
  166. } huft;
  167.  
  168. /* Function prototypes */
  169. static void huft_free  __ARGS__((huft **));
  170. static int  huft_build __ARGS__((unsigned *, unsigned, unsigned, ush *, ush *,
  171.                                  huft **, int *));
  172. static void copyout __ARGS__((void));
  173. static ush getbits __ARGS__((ush));
  174. static int decode  __ARGS__((unsigned *, huft *, int));
  175. static int inflate_codes __ARGS__((unsigned));
  176. static int inflate_dynamic __ARGS__((unsigned));
  177. static int inflate_fixed   __ARGS__((unsigned));
  178. static int inflate_stored  __ARGS__((unsigned));
  179. static ush getsh __ARGS__((void));
  180. static ulg getlg __ARGS__((void));
  181. static int skip __ARGS__((int));
  182.  
  183. /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
  184.    stream to find repeated byte strings.  This is implemented here as a
  185.    circular buffer.  The index is updated simply by incrementing and then
  186.    and'ing with 0x7fff (32K-1). */
  187. /* It is left to other modules to supply the 32K area.  It is assumed
  188.    to be usable as if it were declared "uch slide[32768];" or as just
  189.    "uch *slide;" and then malloc'ed in the latter case.  The definition
  190.    must be in unzip.h, included above. */
  191. unsigned wp;            /* current position in slide */
  192.  
  193. /* Tables for deflate from PKZIP's appnote.txt. */
  194. static unsigned border[] = {    /* Order of the bit length code lengths */
  195.         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  196. static ush cplens[] = {         /* Copy lengths for literal codes 257..285 */
  197.         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  198.         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  199.         /* note: see note #13 above about the 258 in this list. */
  200. static ush cplext[] = {         /* Extra bits for literal codes 257..285 */
  201.         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  202.         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
  203. static ush cpdist[] = {         /* Copy offsets for distance codes 0..29 */
  204.         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  205.         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  206.         8193, 12289, 16385, 24577};
  207. static ush cpdext[] = {         /* Extra bits for distance codes */
  208.         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  209.         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  210.         12, 12, 13, 13};
  211.  
  212. /* Macros for inflate() bit peeking and grabbing.
  213.    The usage is:
  214.  
  215.         NEEDBITS(j)
  216.         x = b & mask_bits[j];
  217.         DUMPBITS(j)
  218.  
  219.    where NEEDBITS makes sure that b has at least j bits in it, and
  220.    DUMPBITS removes the bits from b.  The macros use the variable k
  221.    for the number of bits in b.  Normally, b and k are register
  222.    variables for speed, and are initialized at the begining of a
  223.    routine that uses these macros from a global bit buffer and count.
  224.  
  225.    If we assume that EOB will be the longest code, then we will never
  226.    ask for bits with NEEDBITS that are beyond the end of the stream.
  227.    So, NEEDBITS should not read any more bytes than are needed to
  228.    meet the request.  Then no bytes need to be "returned" to the buffer
  229.    at the end of the last block.
  230.  
  231.    However, this assumption is not true for fixed blocks--the EOB code
  232.    is 7 bits, but the other literal/length codes can be 8 or 9 bits.
  233.    (The EOB code is shorter than other codes becuase fixed blocks are
  234.    generally short.  So, while a block always has an EOB, many other
  235.    literal/length codes have a significantly lower probability of
  236.    showing up at all.)  However, by making the first table have a
  237.    lookup of seven bits, the EOB code will be found in that first
  238.    lookup, and so will not require that too many bits be pulled from
  239.    the stream.
  240.  */
  241.  
  242. static ulg bb;      /* bit buffer */
  243. static unsigned bk; /* bits in bit buffer */
  244.  
  245. #define NEEDBITS(n) {while(k<(n)){b|=((ulg)nextbyte())<<k;k+=8;}}
  246. #define DUMPBITS(n) {b>>=(n);k-=(n);}
  247. /* A reasonable optimization for 16-bits computers */
  248. #define NEEDTINY(n) {if(k<(n)){b|=(unsigned)nextbyte()<<k;k+=8;}}
  249. #define DUMPTINY(n) {b=(unsigned)b>>(n);k-=(n);}
  250.  
  251. static ush mask_bits[] = {
  252.    0x0000,
  253.    0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
  254.    0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
  255. };
  256.  
  257. /*
  258.    Huffman code decoding is performed using a multi-level table lookup.
  259.    The fastest way to decode is to simply build a lookup table whose
  260.    size is determined by the longest code.  However, the time it takes
  261.    to build this table can also be a factor if the data being decoded
  262.    is not very long.  The most common codes are necessarily the
  263.    shortest codes, so those codes dominate the decoding time, and hence
  264.    the speed.  The idea is you can have a shorter table that decodes the
  265.    shorter, more probable codes, and then point to subsidiary tables for
  266.    the longer codes.  The time it costs to decode the longer codes is
  267.    then traded against the time it takes to make longer tables.
  268.  
  269.    This results of this trade are in the variables lbits and dbits
  270.    below.  lbits is the number of bits the first level table for literal/
  271.    length codes can decode in one step, and dbits is the same thing for
  272.    the distance codes.  Subsequent tables are also less than or equal to
  273.    those sizes.  These values may be adjusted either when all of the
  274.    codes are shorter than that, in which case the longest code length in
  275.    bits is used, or when the shortest code is *longer* than the requested
  276.    table size, in which case the length of the shortest code in bits is
  277.    used.
  278.  
  279.    There are two different values for the two tables, since they code a
  280.    different number of possibilities each.  The literal/length table
  281.    codes 286 possible values, or in a flat code, a little over eight
  282.    bits.  The distance table codes 30 possible values, or a little less
  283.    than five bits, flat.  The optimum values for speed end up being
  284.    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
  285.    The optimum values may differ though from machine to machine, and
  286.    possibly even between compilers.  Your mileage may vary.
  287.  */
  288. #if 0
  289. int lbits = 9; /* bits in base literal/length lookup table */
  290. int dbits = 6; /* bits in base distance lookup table */
  291. #else
  292. #define lbits 9
  293. #define dbits 6
  294. #endif
  295.  
  296. static void huft_free(t)
  297. huft **t; /* table to free */
  298. /* Free the malloc'ed tables built by huft_build(), which makes a linked
  299.    list of the tables it made, with the links in a dummy first entry of
  300.    each table. */
  301. {
  302.    register huft *p, *q;
  303.  
  304.    /* Go through linked list, freeing from the malloced (t[-1]) address. */
  305.    p = *t;
  306.    while (p) {
  307.       q = (--p)->v.t;
  308.       free(p);
  309.       p = q;
  310.    }
  311.    *t = NULL;
  312. }
  313.  
  314. /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
  315. #define BMAX 16   /* maximum bit length of any code (16 for explode) */
  316. #define N_MAX 288 /* maximum number of codes in any set */
  317. #ifdef DEBUG
  318. unsigned hufts;   /* track memory usage */
  319. #endif
  320.  
  321. static int huft_build(b, n, s, d, e, t, m)
  322. unsigned *b; /* code lengths in bits (all assumed <= BMAX) */
  323. unsigned n;  /* number of codes (assumed <= N_MAX) */
  324. unsigned s;  /* number of simple-valued codes (0..s-1) */
  325. ush *d;      /* list of base values for non-simple codes */
  326. ush *e;      /* list of extra bits for non-simple codes */
  327. huft **t;    /* result: starting table */
  328. int *m;      /* maximum lookup bits, returns actual */
  329. /* Given a list of code lengths and a maximum table size, make a set of
  330.    tables to decode that set of codes.  Return zero on success, one if
  331.    the given code set is incomplete (the tables are still built in this
  332.    case), two if the input is invalid (all zero length codes or an
  333.    oversubscribed set of lengths), and three if not enough memory. */
  334. {
  335.   unsigned a;           /* counter for codes of length k */
  336.   unsigned c[BMAX+1];   /* bit length count table */
  337.   unsigned f;           /* i repeats in table every f entries */
  338.   int g;                /* maximum code length */
  339.   int h;                /* table level */
  340.   register unsigned i;  /* counter, current code */
  341.   register unsigned j;  /* counter */
  342.   register int k;       /* number of bits in current code */
  343.   int l;                /* bits per table (returned in m) */
  344.   register unsigned *p; /* pointer into c[], b[], or v[] */
  345.   register huft *q;     /* points to current table */
  346.   huft r;               /* table entry for structure assignment */
  347.   huft *u[BMAX];        /* table stack */
  348.   unsigned v[N_MAX];    /* values in order of bit length */
  349.   register int w;       /* bits before this table == (l * h) */
  350.   unsigned x[BMAX+1];   /* bit offsets, then code stack */
  351.   unsigned *xp;         /* pointer into x */
  352.   int y;                /* number of dummy codes added */
  353.   unsigned z;           /* number of entries in current table */
  354.  
  355.   /* Generate counts for each bit length */
  356.   for (i=0; i<=BMAX; i++) c[i] = 0;
  357.   p = b;  i = n;
  358.   do {
  359.     c[*p++]++;     /* assume all entries <= BMAX */
  360.   } while (--i);
  361.   if (c[0] == n) { /* null input--all zero length codes */
  362.     *t = (huft *)NULL;
  363.     *m = 0;
  364.     return 0;
  365.   }
  366.  
  367.   /* Find minimum and maximum length, bound *m by those */
  368.   l = *m;
  369.   for (j = 1; j <= BMAX && !c[j]; j++);
  370.   k = j; /* minimum code length */
  371.   if ((unsigned)l < j) l = j;
  372.   for (i = BMAX; i && !c[i]; i--);
  373.   g = i; /* maximum code length */
  374.   if ((unsigned)l > i) l = i;
  375.   *m = l;
  376.  
  377.   /* Adjust last length count to fill out codes, if needed */
  378.   for (y = 1 << j; j < i; j++, y <<= 1)
  379.     if ((y -= c[j]) < 0) return 2; /* bad input: more codes than bits */
  380.   if ((y -= c[i]) < 0) return 2;
  381.   c[i] += y;
  382.  
  383.   /* Generate starting offsets into the value table for each length */
  384.   x[1] = j = 0;
  385.   p = c + 1;  xp = x + 2;
  386.   while (--i) {                 /* note that i == g from above */
  387.     *xp++ = (j += *p++);
  388.   }
  389.  
  390.   /* Make a table of values in order of bit lengths */
  391.   p = b;  i = 0;
  392.   do {
  393.     if ((j = *p++) != 0) v[x[j]++] = i;
  394.   } while (++i < n);
  395.  
  396.   /* Generate the Huffman codes and for each, make the table entries */
  397.   x[0] = i = 0;        /* first Huffman code is zero */
  398.   p = v;               /* grab values in bit order */
  399.   h = -1;              /* no tables yet--level -1 */
  400.   w = -l;              /* bits decoded == (l * h) */
  401.   u[0] = (huft *)NULL; /* just to keep compilers happy */
  402.   q = (huft *)NULL;    /* ditto */
  403.   z = 0;               /* ditto */
  404.  
  405.   /* go through the bit lengths (k already is bits in shortest code) */
  406.   for (; k <= g; k++) {
  407.     a = c[k];
  408.     while (a--) {
  409.       /* here i is the Huffman code of length k bits for value *p */
  410.       /* make tables up to required level */
  411.       while (k > w + l) {
  412.         h++;
  413.         w += l;                 /* previous table always l bits */
  414.  
  415.         /* compute minimum size table less than or equal to l bits */
  416.         z = (z = g - w) > (unsigned)l ? l : z;  /* upper limit on table size */
  417.         if ((f = 1 << (j = k - w)) > a + 1) {   /* try a k-w bit table */
  418.           f -= a + 1;           /* too few codes for k-w bit table */
  419.           xp = c + k;           /* deduct codes from patterns left */
  420.           while (++j < z) {     /* try smaller tables up to z bits */
  421.             if ((f <<= 1) <= *++xp)
  422.               break;            /* enough codes to use up j bits */
  423.             f -= *xp;           /* else deduct codes from patterns */
  424.           }
  425.         }
  426.         z = 1 << j;             /* table entries for j-bit table */
  427.  
  428.         /* allocate and link in new table */
  429.         q = (huft *)malloc((z + 1)*sizeof(huft));
  430.         if (!q) {/* not enough memory */
  431.           if (h) huft_free(u); return (ziperror=ZNOMEM, ERROR);
  432.         }
  433. #ifdef DEBUG
  434.         hufts += z + 1;         /* track memory usage */
  435. #endif
  436.         *t = q + 1;             /* link to list for huft_free() */
  437.         *(t = &(q->v.t)) = (huft *)NULL;
  438.         u[h] = ++q;             /* table starts after link */
  439.  
  440.         /* connect to last table, if there is one */
  441.         if (h) {
  442.           x[h] = i;             /* save pattern for backing up */
  443.           r.b = (uch)l;         /* bits to dump before this table */
  444.           r.e = (uch)(16 + j);  /* bits in this table */
  445.           r.v.t = q;            /* pointer to this table */
  446.           j = i >> (w - l);     /* (get around Turbo C bug) */
  447.           u[h-1][j] = r;        /* connect to last table */
  448.         }
  449.       }
  450.  
  451.       /* set up table entry in r */
  452.       r.b = (uch)(k - w);
  453.       if (p >= v + n) {
  454.         r.e = 99;               /* out of values--invalid code */
  455.       } else if (*p < s) {
  456.         r.e = (uch)(*p < 256 ? 16 : 15);    /* 256 is end-of-block code */
  457.         r.v.n = *p++;           /* simple code is just the value */
  458.       } else {
  459.         r.e = (uch)e[*p - s];   /* non-simple--look up in lists */
  460.         r.v.n = d[*p++ - s];
  461.       }
  462.  
  463.       /* fill code-like entries with r */
  464.       f = 1 << (k - w);
  465.       for (j = i >> w; j < z; j += f) q[j] = r;
  466.  
  467.       /* backwards increment the k-bit code i */
  468.       for (j = 1 << (k - 1); i & j; j >>= 1) i ^= j;
  469.       i ^= j;
  470.  
  471.       /* backup over finished tables */
  472.       while ((i & ((1 << w) - 1)) != x[h]) {
  473.         h--; /* don't need to update q */
  474.         w -= l;
  475.       }
  476.     }
  477.   }
  478.   /* Return true (1) if we were given an incomplete table */
  479.   return y != 0 && g != 1;
  480. }
  481.  
  482. static void copyout()
  483. {
  484.    register unsigned length;
  485.  
  486.    if ((length = wp - outpos) != 0) {
  487.       updcrc(slide+outpos, length);
  488. #ifdef NOMEMCPY
  489.       while (length--) *outbuf++ = (char)slide[outpos++];
  490. #else
  491.       (void)memcpy(outbuf, slide+outpos, length);
  492.       outbuf += length;
  493.       outpos += length;
  494. #endif
  495.       outsiz += length;
  496.    }
  497. }
  498.  
  499. static ush getbits(n)
  500. ush n; /* number of bits to get */
  501. {
  502.    register ulg b;      /* bit buffer */
  503.    register unsigned k; /* number of bits in bit buffer */
  504.    register unsigned j;
  505.  
  506.    /* make local copies of globals */
  507.    b = bb; k = bk;
  508.    NEEDBITS(n);
  509.    j = (unsigned)b & mask_bits[n];
  510.    DUMPBITS(n);
  511.    /* restore the globals from the locals */
  512.    bk = k; bb = b;
  513.    return j;
  514. }
  515.  
  516. static int decode(np, t, bn)
  517. unsigned *np; /* decoded value */
  518. huft *t;      /* tree to decode */
  519. int bn;       /* bits number */
  520. /* Returns number of extra bits (BAD on error). */
  521. {
  522.    register ulg b;      /* bit buffer */
  523.    register unsigned k; /* number of bits in bit buffer */
  524.  
  525.    /* make local copies of globals */
  526.    b = bb; k = bk;
  527.    for (;;) {
  528.       NEEDBITS((unsigned)bn)
  529.       t += ((unsigned)b & mask_bits[bn]);
  530.       if ((bn = t->e) == BAD) goto end;
  531.       DUMPBITS(t->b)
  532.       if (bn <= 16) break;
  533.       t = t->v.t;
  534.       bn -= 16;
  535.    }
  536.    *np = t->v.n;
  537.    /* restore the globals from the locals */
  538.    bk = k; bb = b;
  539. end:
  540.    return bn;
  541. }
  542.  
  543. static huft *tl = NULL; /* literal/length code table */
  544. static huft *td = NULL; /* distance code table */
  545. static int bl;          /* lookup bits for tl */
  546. static int bd;          /* lookup bits for td */
  547.  
  548. static int inflate_codes(length)
  549. unsigned length;
  550. /* inflate (decompress) the codes in a deflated (compressed) block.
  551.    Return an number of bytes decompressed or ERROR. */
  552. {
  553.    register unsigned i;
  554.    register unsigned e; /* number of extra bits */
  555.    static unsigned n,d; /* length and index for copy */
  556.  
  557.    for (i=0; i<length;) {
  558.       if (!(zipstate & ICFLAG)) {
  559.          if ((e = decode(&n, tl, bl)) == BAD)
  560.             return (ziperror=ZMOULD, ERROR);
  561.          if (e == LITERAL) {
  562.             slide[wp++] = (uch)n;
  563.             if (wp >= WSIZE) {
  564.                copyout(); outpos = wp = 0;
  565.             }
  566.             ++i;
  567.             continue;
  568.          }
  569.          if (e == EOB) {
  570.             /* clear all unneccesary flags & exit */
  571.             zipstate &= AT_EOF|INITED; break;
  572.          }
  573.          /* Length code encountered, get length of block to copy */
  574.          n += getbits(e);
  575.          /* decode distance of block to copy */
  576.          if ((e = decode(&d, td, bd)) == BAD)
  577.             return (ziperror=ZMOULD, ERROR);
  578.          d = wp - (d + getbits(e));
  579.       }
  580.       zipstate &= ~ICFLAG;
  581.       /* do the copy */
  582.       do {
  583.          d &= WSIZE-1;
  584.          if ((e = WSIZE - max(d,wp)) > n) e = n;
  585.          if (i+e > length) {
  586.             zipstate |= ICFLAG; e = length-i;
  587.          }
  588.          i += e;
  589.          n -= e;
  590.  #ifndef NOMEMCPY
  591.          if (wp - d >= e) {/* (this test assumes unsigned comparison) */
  592.             memcpy(slide + wp, slide + d, e);
  593.             wp += e;
  594.             d += e;
  595.          } else /* do it slow to avoid memcpy() overlap */
  596.  #endif /* !NOMEMCPY */
  597.             do slide[wp++] = slide[d++]; while (--e);
  598.          if (wp >= WSIZE) {
  599.             copyout(); outpos = wp  = 0;
  600.          }
  601.       } while (n && !(zipstate & ICFLAG));
  602.    }
  603.    copyout();
  604.    return i;
  605. }
  606.  
  607. static int inflate_dynamic(length)
  608. unsigned length;
  609. /* decompress an inflated type 2 (dynamic Huffman codes) block. */
  610. /* Returns number of bytes decompressed or ERROR. */
  611. {
  612.    register i;
  613.  
  614.    if (!(zipstate & IBEGIN)) {
  615.       unsigned j;
  616.       unsigned l;  /* last length */
  617.       unsigned m;  /* mask for bit lengths table */
  618.       unsigned n;  /* number of lengths to get */
  619.       unsigned nb; /* number of bit length codes */
  620.       unsigned nl; /* number of literal/length codes */
  621.       unsigned nd; /* number of distance codes */
  622. #ifdef PKZIP_BUG_WORKAROUND
  623.       unsigned ll[288+32]; /* literal/length and distance code lengths */
  624. #else
  625.       unsigned ll[286+30]; /* literal/length and distance code lengths */
  626. #endif
  627.       register ulg b;      /* bit buffer */
  628.       register unsigned k; /* number of bits in bit buffer */
  629.  
  630.       /* make local bit buffer */ b = bb; k = bk;
  631.  
  632.       /* read in table lengths */
  633.       NEEDTINY(5)
  634.       nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */
  635.       DUMPTINY(5)
  636.       NEEDTINY(5)
  637.       nd = 1 + ((unsigned)b & 0x1f);   /* number of distance codes */
  638.       DUMPTINY(5)
  639.       NEEDTINY(4)
  640.       nb = 4 + ((unsigned)b & 0xf);    /* number of bit length codes */
  641.       DUMPTINY(4)
  642. #ifdef PKZIP_BUG_WORKAROUND
  643.       if (nl > 288 || nd > 32)
  644. #else
  645.       if (nl > 286 || nd > 30)
  646. #endif
  647.         return (ziperror=ZMOULD, ERROR); /* bad lengths */
  648.  
  649.       /* read in bit-length-code lengths */
  650.       for (j = 0; j < nb; j++) {
  651.         NEEDTINY(3)
  652.         ll[border[j]] = (unsigned)b & 7;
  653.         DUMPTINY(3)
  654.       }
  655.       for (; j < 19; j++) ll[border[j]] = 0;
  656.  
  657.       /* build decoding table for trees--single level, 7 bit lookup */
  658.       bl = 7;
  659.       if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
  660.          if (i != ERROR) /* all save memory lack */ ziperror = ZMOULD;
  661.          if (i == TRUE) /* incomplete code set */ huft_free(&tl);
  662.          return ERROR;
  663.       }
  664.  
  665.       /* read in literal and distance code lengths */
  666.       n = nl + nd;
  667.       m = mask_bits[bl];
  668.       i = l = 0;
  669.       while ((unsigned)i < n) {
  670.         NEEDBITS((unsigned)bl)
  671.         j = (td = tl + ((unsigned)b & m))->b;
  672.         DUMPBITS(j)
  673.         j = td->v.n;
  674.         if (j < 16) {      /* length of code in bits (0..15) */
  675.           ll[i++] = l = j; /* save last length in l */
  676.         } else {
  677.           if (j == 16) {/* repeat last length 3 to 6 times */
  678.             NEEDTINY(2)
  679.             j = 3 + ((unsigned)b & 3);
  680.             DUMPTINY(2)
  681.           } else {
  682.             l = 0;
  683.             if (j == 17) {/* 3 to 10 zero length codes */
  684.               NEEDTINY(3)
  685.               j = 3 + ((unsigned)b & 7);
  686.               DUMPTINY(3)
  687.             } else {/* j == 18: 11 to 138 zero length codes */
  688.               NEEDTINY(7)
  689.               j = 11 + ((unsigned)b & 0x7f);
  690.               DUMPTINY(7)
  691.             }
  692.           }
  693.           if ((unsigned)i + j > n) return (ziperror=ZMOULD, ERROR);
  694.           while (j--) ll[i++] = l;
  695.         }
  696.       }
  697.  
  698.       /* free decoding table for trees */
  699.       huft_free(&tl);
  700.  
  701.       /* restore the global bit buffer */
  702.       bb = b;
  703.       bk = k;
  704.  
  705.       /* build the decoding tables for literal/length and distance codes */
  706.       bl = lbits;
  707.       if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
  708.          if (i != ERROR) /* all save memory lack */ ziperror = ZMOULD;
  709.          if (i == TRUE) /* incomplete literal tree */ huft_free(&tl);
  710.          return ERROR;
  711.       }
  712.       bd = dbits;
  713.       if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
  714. #ifndef PKZIP_BUG_WORKAROUND
  715.          if (i == TRUE) huft_free(&td); /* incomplete distance tree */
  716. #else
  717.          if (i != TRUE)
  718. #endif
  719.          {
  720.             huft_free(&tl);
  721.             if (i != ERROR) ziperror = ZMOULD;
  722.             return ERROR;
  723.          }
  724.       }
  725.       zipstate |= IBEGIN;
  726.    }
  727.    if ((i = inflate_codes(length)) == ERROR || !(zipstate & IBEGIN)) {
  728.       huft_free(&tl); huft_free(&td);
  729.    }
  730.    return i;
  731. }
  732.  
  733. static int inflate_fixed(length)
  734. unsigned length;
  735. /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
  736.    either replace this with a custom decoder, or at least precompute the
  737.    Huffman tables. */
  738. /* Returns number of bytes decompressed or ERROR. */
  739. {
  740.    register i;
  741.  
  742.    if (!(zipstate & IBEGIN)) {
  743.       unsigned l[288]; /* length list for huft_build */
  744.  
  745.       i = 0;
  746.       /* set up literal table; make a complete, but wrong code set */
  747.       do l[i] = 8; while (++i < 144);
  748.       do l[i] = 9; while (++i < 256);
  749.       do l[i] = 7; while (++i < 280);
  750.       do l[i] = 8; while (++i < 288);
  751.  
  752.       bl = 7;
  753.       if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0) {
  754.          if (i != ERROR) /* all save memory lack */ ziperror = ZERROR;
  755.          if (i == TRUE) /* incomplete code set */ huft_free(&tl);
  756.          return ERROR;
  757.       }
  758.  
  759.       /* set up distance table */
  760.       for (i=0; i<30; i++) l[i] = 5; /* make an incomplete code set */
  761.  
  762.       bd = 5;
  763.       if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) & ~1) {
  764.          if (i != ERROR) ziperror = ZERROR;
  765.          huft_free(&tl);
  766.          return ERROR;
  767.       }
  768.    }
  769.    if ((i = inflate_codes(length)) == ERROR || !(zipstate & IBEGIN)) {
  770.       huft_free(&tl); huft_free(&td);
  771.    }
  772.    return i;
  773. }
  774.  
  775. static int inflate_stored(length)
  776. unsigned length;
  777. /* "decompress" an inflated type 0 (stored) block. */
  778. /* Returns number of bytes restored or ERROR. */
  779. {
  780.    static unsigned n; /* number of bytes to copy */
  781.    register unsigned i;
  782.  
  783.    if (!(zipstate & IBEGIN)) {
  784.       if (bk > 7) /* fail to align bit buffer */
  785.          return (ziperror=ZERROR, ERROR);
  786.       /* go to byte boundary */
  787.       bb = 0; /* bit buffer */
  788.       bk = 0; /* number of bits in bit buffer */
  789.  
  790.       /* get the length and its complement */
  791.       n = nextbyte(); n |= nextbyte() << 8;
  792.       i = nextbyte(); i |= nextbyte() << 8;
  793.       if (n != (i ^ 0xffff)) /* data error */
  794.          return (ziperror=ZMOULD, ERROR);
  795.    }
  796.    /* read and output the "compressed" data */
  797.    for (i=0; i<length; i++) {
  798.       if (n-- == 0) {
  799.          /* End of block - clear method and other unneccesary flags */
  800.          zipstate &= AT_EOF|INITED;
  801.          break;
  802.       }
  803.       slide[wp++] = (uch)nextbyte();
  804.       if (wp >= WSIZE) {
  805.          copyout(); outpos = wp = 0;
  806.       }
  807.    }
  808.    copyout();
  809.    return i;
  810. }
  811.  
  812. static int skip(n)
  813. register int n;
  814. {
  815.    while (n--) if (readbyte()==EOF) return EOF; return 0;
  816. }
  817.  
  818. static ush getsh()
  819. {
  820.    register ush i; i = readbyte(); return i | (readbyte() << 8);
  821. }
  822.  
  823. static ulg getlg()
  824. {
  825.    register ush i = 0;
  826.    register ulg l = 0;
  827.  
  828.    if (bk) {
  829.       i = bk & ~7;
  830.       l = bb >> (bk & 7);
  831.       bb = 0;
  832.       bk = 0;
  833.    }
  834.    for (; i<32; i+=8) l |= (ulg)readbyte() << i;
  835.    return l;
  836. }
  837.  
  838. int unzalloc()
  839. {
  840.    if (!slide) slide = (uch*)malloc(WSIZE); return !slide;
  841. }
  842.  
  843. int unzopen(getbyte, ztype)
  844. int ztype, (*getbyte)();
  845. {
  846.    ziperror = 0;
  847.    if (unzalloc()) return (ziperror = ZNOMEM);
  848.    getb = getbyte;
  849.    zipstate = 0;
  850.    ziptype = ztype;
  851.    outsiz = 0L;
  852.    /* Initialise CRC calculations */
  853.    crcbegin();
  854.    /* Initialise deflate */
  855.    wp = 0; bb = 0; bk = 0;
  856.    outpos = 0;
  857.    return 0;
  858. }
  859.  
  860. int unzread(buffer, length)
  861. char *buffer; unsigned length;
  862. {
  863.    register i;
  864.    register unsigned j, k;
  865.    register ulg b;
  866.  
  867.    if (!(zipstate & INITED)) {/* Read and decode header */
  868.       if (!slide || !getb) return (ziperror = ZNOPEN, ERROR);
  869.  
  870.       if (ziptype == ZIP_RAW) {
  871.          zmethod = DEFLATED;
  872.       } else {
  873.          /* Check for zip type */
  874.          k = getsh();
  875.          if        (ziptype == ZIP_GNU) {
  876.             if (k != GZIP_MAGIC) return ZMAGIC;
  877.          } else if (ziptype == ZIP_PKW) {
  878.             if (k!=PKW_01_MAGIC || getsh()!=PKW_23_MAGIC) return ZMAGIC;
  879.          } else {
  880.             if (k==PKW_01_MAGIC && getsh()==PKW_23_MAGIC) ziptype=ZIP_PKW;
  881.             else if (k == GZIP_MAGIC)                     ziptype=ZIP_GNU;
  882.             else return ZMAGIC;
  883.          }
  884.          /* Decode header */
  885.          if (ziptype == ZIP_GNU) {
  886.             zmethod  = readbyte();
  887.             if ((zipflags = readbyte()) & (GF_ERROR|GF_CRYPT|GF_CONT))
  888.                return ZUNSUP;
  889.             /* Skip file time, extra flags and OS type */
  890.             if (skip(6)) return ZHDEOF;
  891. #if 0
  892.             if (zipflags & GF_CONT) {
  893.                /* Skip the part number */ if (skip(2)) return ZHDEOF;
  894.             }
  895. #endif
  896.             if (zipflags & GF_EXTRA) {/* Skip the extra field */
  897.                k = getsh(); if (skip(k)) return ZHDEOF;
  898.             }
  899.             if (zipflags & GF_FNAME) {/* Skip the file name */
  900.                do if ((i=readbyte()) == EOF) return ZHDEOF; while (i);
  901.             }
  902.             if (zipflags & GF_COMMENT) {/* Skip comment */
  903.                do if ((i=readbyte()) == EOF) return ZHDEOF; while (i);
  904.             }
  905.          } else {/* PKWARE */
  906.             if (skip(2)) return ZHDEOF; /* version to extract */
  907.             if ((zipflags = getsh()) & (PF_ERROR|PF_CRYPT)) return ZUNSUP;
  908.             zmethod  = getsh();
  909.             if (skip(4)) return ZHDEOF; /* skip file time/date */
  910.             crc32val = getlg();
  911.             (void)     getlg(); /* Ignore packed size */
  912.             srcsize  = getlg();
  913.             k = getsh(); /* file name length */
  914.             j = getsh(); /* extra field length */
  915.             if (/* header length */30L + k + j > 65535L || skip(k+j))
  916.                return ZHDEOF;
  917.          }
  918.          /* Header decoded */
  919.       }
  920.       zipstate |= INITED;
  921.    }
  922.    if (zmethod == DEFLATED) {
  923.       outbuf = buffer;
  924.       j = 0;
  925.       do {
  926.          if (!(zipstate & METHOD)) {
  927.             if (zipstate & AT_EOF) break;
  928.  
  929.             /* make local bit buffer */
  930.             b = bb; k = bk;
  931.  
  932.             /* read in last block bit */
  933.             NEEDTINY(1)
  934.             if ((int)b & 1) zipstate |= AT_EOF;
  935.             DUMPTINY(1)
  936.  
  937.             /* read in block type */
  938.             NEEDTINY(2)
  939.             if ((i = ((int)b & 3) + 1) & ~METHOD)
  940.                return (ziperror=ZMOULD, ERROR);
  941.             DUMPTINY(2)
  942.             zipstate |= i;
  943.  
  944.             /* restore the global bit buffer */
  945.             bb = b; bk = k;
  946.          }
  947.          k = length - j;
  948.          switch (zipstate & METHOD) {
  949.             case 3 : i = inflate_dynamic(k); break;
  950.             case 2 : i = inflate_fixed  (k); break;
  951.             case 1 : i = inflate_stored (k); break;
  952.             default: ziperror = ZMOULD; return ERROR;
  953.          }
  954.          if (i == ERROR) return i;
  955.       } while ((i || !(zipstate & AT_EOF)) && (j+=i) < length);
  956.       return j;
  957.    }
  958. #if 0
  959.    else if (ziptype == Z_PKW && zmethod == STORED) ;
  960. #endif
  961.    ziperror = ZUNSUP;
  962.    return ERROR;
  963. }
  964.  
  965. void unzfree()
  966. {
  967.    if (slide) { free(slide); slide = (uch*)0; }
  968.    if (tl) huft_free(&tl);
  969.    if (td) huft_free(&td);
  970. }
  971.  
  972. int unzclose()
  973. {
  974.    int k = ERROR;  /* return value */
  975.    int i = 0;      /* bytes rest */
  976.    register ulg l; /* working variable */
  977.  
  978.    ziperror = ZNOPEN;
  979.    if (!slide || !getb || !(zipstate & INITED)) goto end;
  980.  
  981.    if (!(zipstate & AT_EOF)) {
  982.       /* Indicate warning message */ k = (ziperror=ZNOEOF); goto end;
  983.    }
  984.    if (zipstate & METHOD) {
  985.       char b[16]; register j;
  986.       /* skip the rest of data */
  987.       while ((j=unzread(b, sizeof(b))) == sizeof(b)) i += j;
  988.       if (j == ERROR) goto end;
  989.    }
  990.    if (ziptype != ZIP_RAW) {
  991.       if        (ziptype == ZIP_GNU) {
  992.          crc32val = getlg();
  993.          srcsize  = getlg();
  994.       } else if (ziptype == ZIP_PKW) {
  995.          if (zipflags & PF_ATEOF) {
  996. #ifdef V314_BUG_WORKAROUND
  997.             if ((l = getlg()) == PKW_EXT) {
  998.                if ((crc32val = getlg()) == getcrc()) {
  999.                   (void)    getlg(); /* Skip the packed size */
  1000.                   srcsize = getlg();
  1001.                   goto crc_ok;
  1002.                }
  1003.             } else {
  1004.                (void)getlg(); /* Skip the packed size */
  1005.             }
  1006.             crc32val = l;
  1007. #else
  1008.             if (getlg() != PKW_EXT) { lzerror = ZMOULD; goto end; }
  1009.             crc32val = getlg();
  1010.             (void)     getlg(); /* Ignore packed size */
  1011. #endif
  1012.             srcsize  = getlg();
  1013.          }
  1014.       } else {
  1015.          ziperror = ZNOPEN; goto end;
  1016.       }
  1017.       if (crc32val != getcrc()) { ziperror = BADCRC; goto end; }
  1018. crc_ok:
  1019.       if (outsiz   !=  srcsize) { ziperror = ZBADSZ; goto end; }
  1020.  
  1021.       if (ziptype == ZIP_PKW) {
  1022.          /* Test for the end of archive */
  1023.          if ((l = getlg()) != PKW_CENTRAL) {
  1024.             /* Indicate warning message */
  1025.             k = (ziperror = l==PKW_LOCAL ? ZNOEOF : ZMOULD);
  1026.             goto end;
  1027.          }
  1028.       }
  1029.    }
  1030.    k = i ? (ziperror = ZNOEOF) : 0; /* 0 means normal close */
  1031. end:
  1032.    unzfree();
  1033.    zipstate = 0;
  1034.    getb = NULL;
  1035.    return k;
  1036. }
  1037.